const cloud = require('wx-server-sdk')

cloud.init()
function addPreZero (num, len = 2) {
	var t = (num + '').length,
		s = '';
	for (var i = 0; i < len - t; i++) {
		s += '0';
	}
	return s + num;
}
const db = cloud.database()
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
		rule_appointsetting: true
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id == 3 || (staff.group_id == 2 && !staff.rule_appointsetting)) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	let time_begin = new Date(event.time_begin)

	time_begin.setMinutes(time_begin.getMinutes()-480-time_begin.getTimezoneOffset())
	let time_end = new Date(event.time_end)
	time_end.setMinutes(time_end.getMinutes()-480-time_end.getTimezoneOffset())
	let time_result = new Date(event.time_result)
	time_result.setMinutes(time_result.getMinutes()-480-time_result.getTimezoneOffset())
	let data = {
		shop_id: event.shop_id,
		product_id: event.product_id,
		year: event.year,
		month: event.month,
		day: event.day,
		is_allow: event.is_allow,
		time_begin,
		time_end,
		time_result,
		type: event.type,
		date:event.year+'-'+addPreZero(event.month)+'-'+addPreZero(event.day)
	}
	console.log(event,data)
	let where = {
		shop_id: event.shop_id,
		product_id: event.product_id,
		year: event.year,
		month: event.month,
		day: event.day
	}
	let daily = await db.collection('daily').field({
		_id: true
	}).where(where).get()
	let daily_id;
	if (daily.data.length == 0) {
		data.result_status = false
		//add
		await db.collection('daily').add({
			data
		}).then(res => {
			daily_id = res._id
		})
	} else {
		daily_id = daily.data[0]._id
		//update
		await db.collection('daily').where(where).update({
			data
		})
	}
	console.log('daily_id:',daily_id)
	await event.timelines.forEach(n => {
		let timeline = {
			time_begin: n.time_begin,
			time_end: n.time_end,
			nums_limit: n.nums_limit,
			nums_max: n.nums_max,
		}
		//console.log(n)
		if (n.delete) {
			return db.collection('timeline').where({
				shop_id: event.shop_id,
				product_id: event.product_id,
				daily_id: daily_id,
				_id: n._id
			}).remove()
		}
		if (n._id) {
			db.collection('timeline').where({
				shop_id: event.shop_id,
				product_id: event.product_id,
				daily_id: daily_id,
				_id: n._id
			}).update({data:timeline})
		} else {
			timeline.shop_id = event.shop_id
			timeline.product_id = event.product_id
			timeline.daily_id = daily_id
			timeline.nums_cnt = 0
			timeline.result_status = 1
			db.collection('timeline').add({
				data: timeline
			})
		}

	})
	console.log(daily_id, event)
	//处理timeline
	return {
		code: 200,
		msg: '设置成功'
	}
}